<template>
    <div class="goods-add-form">
        <div class="section">
            <h2 class="section-title">出库基本信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="othoutord_order" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <el-form-item label="出库单号" prop="othoutord_code">
                    <el-input v-model="othoutord_order.othoutord_code" placeholder="不输入则自动获取编号" />
                </el-form-item>
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="出库类型" prop="othoutord_type" style="margin-bottom: 30px;">
                            <el-select v-model="othoutord_order.othoutord_type" placeholder="请选择出库类型"
                                @change="handleSelecttype">
                                <el-option v-for="item in options" :key="item.dict_value" :label="item.dict_label"
                                    :value="item.dict_value" class="option-style" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="出库仓库" prop="warehouse_code" style="margin-bottom: 30px;">
                            <el-select v-model="othoutord_order.warehouse_name" placeholder="请选择出库仓库"
                                @change="handleSelectChange" :disabled="InsertisDisabledlocation">
                                <el-option v-for="item in Weahouse" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>


                        <el-form-item label="出库员" prop="othoutord_wkeep">
                            <el-cascader v-model="othoutord_order.othoutord_wkeep" :options="othoutord_wkeep_List"
                                :props="{ emitPath: false, checkStrictly: false }" :show-all-levels="false"
                                placeholder="请选择部门/人员" clearable filterable style="width: 100%" />
                        </el-form-item>
                    </div>



                    <div style="width: 48%;">
                        <el-form-item label="关联单号" prop="othoutord_code_Associated"
                            style="margin-bottom: 30px; width: 100%;">
                            <el-input v-model="othoutord_order.othoutord_code_Associated" placeholder="请点击输入关联单号"
                                clearable @click="showOrderDialog" readonly class="order-input"
                                style="width: 100%; margin-left: 0px;">
                                <template #append>
                                    <el-button icon="Search" @click="showOrderDialog" />
                                </template>
                            </el-input>
                        </el-form-item>

                        <el-form-item label="出库库区" prop="zone_code" style="margin-bottom: 30px;">
                            <el-select v-model="othoutord_order.zone_name" placeholder="请选择出库库区" @change="handleSzone"
                                style="width:100%" :disabled="InsertisDisabledlocation">
                                <el-option v-for="item in Warhouse_zone" :key="item.zone_code" :label="item.zone_name"
                                    :value="item.zone_code" />
                            </el-select>
                        </el-form-item>

                    </div>
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">出库产品明细</h2>
            <div style="float: left;margin: 10px 0px;">
                <el-button type="primary" @click="productAdd" :disabled='InsertisDisabledlocation'>添加</el-button>
                <el-button @click="productDel" :disabled='InsertisDisabledlocation'>移除</el-button>
            </div>
            <el-table :data="selectedData" border style="width: 93%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="stock_name" label="货品名称" fixed="left" width="100" />
                <el-table-column prop="pro_code" label="货品编号" width="150" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="stock_model" label="规格型号" width="100" />
                <el-table-column prop="dict_code" label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.dict_code) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="location_code" label="出库库位" width="130">
                    <template #default="scope">
                        <el-select v-model="scope.row.location_name" placeholder="选择库位" size="small"
                            :disabled="InsertisDisabledlocation" @change="(val) => locationEndit(val, scope.row)">
                            <el-option v-for="item in Warehouse_location" :key="item.location_code"
                                :label="item.location_name" :value="item.location_code" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="stock_numder" label="当前库存" width="150" />
                <el-table-column prop="inventory_numder" label="未出库数量" width="100">
                    <template #default="scope">
                        <span>{{ scope.row.inventory_numder || 0 }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="出库数量" width="90">
                    <template #default="scope">
                        <el-input v-model="scope.row.sale_qty" style="width: 75px" :precision="2" :min="0"
                            @input="validateSaleQty(scope.row)" />
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="address" label="出库单价" width="90">
                    <template #default="scope">
                        <el-input v-model="scope.row.pro_sale_price" style="width: 75px" :precision="2" :min="0" />
                        <span>{{ scope.row.pro_sale_price }}</span>
                    </template>
                </el-table-column> -->

                <el-table-column prop="address" label="出库单价" width="90">
                    <template #default="scope">
                        <el-input v-model="scope.row.pro_sale_price" style="width: 75px" :precision="2" :min="0" />
                    </template>
                </el-table-column>

                <el-table-column prop="address" label="出库总金额" width="100">
                    <template #default="scope">
                        <span>{{ scope.row.pro_total_amount }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="pro_cost_price" label="成本金额" width="90" />
                <el-table-column prop="address" label="成本合计" width="90">
                    <template #default="scope">
                        <span>{{ scope.row.pro_total_cost }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block;  float:right; margin-right:90px">出库总数量：{{ sale_total_qty }}
                    &nbsp;&nbsp;&nbsp; 出库总金额：{{ Number(sale_total_price).toFixed(2) }}
                    &nbsp;&nbsp;&nbsp;出库产品成本总额：{{ Number(cost_total_proce).toFixed(2) }}
                </div>
            </div>
        </div>

        <div class="button-group"
            style="display: flex;   justify-content: flex-end; gap: 10px; padding: 10px; margin-right: 80px;">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
    <!-- 添加产品模态框 -->
    <el-dialog v-model="dialogTableVisible" width="800" title="添加产品">
        <hr>
        <div style="margin: 10px 0px;">
            <div style="float: left;margin: 10px 0px;">
                <el-input v-model="productName" style="width: 240px;margin-right: 20px;" placeholder="请输入货品编号/名称" />
                <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                    <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                        :value="item.dict_value" />
                </el-select>
            </div>
            <div style="float: right;margin: 10px 0px;">
                <el-button @click="productReaslt">重置</el-button>
                <el-button @click="productEedit">查询</el-button>
            </div>
        </div>
        <el-table ref="multipleTableRef" :data="productData" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="isDisabled" />
            <el-table-column property="pro_code" label="货品编号" width="180" />
            <el-table-column property="stock_name" label="货品名称" width="200" />
            <el-table-column property="stock_model" label="规格型号" />
            <el-table-column property="dict_code" label="单位">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.dict_code) }}</span>
                </template>
            </el-table-column>
            <el-table-column property="pro_cost_price" label="出库单价" />
            <el-table-column property="stock_numder" label="当前库存" />
        </el-table>
        <br>
        <div style="text-align: center;display: flex; justify-content: center;">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>



    <!-- 选择关联单号模态框 -->
    <el-dialog v-model="orderDialogVisible" width="880px" title="选择关联单号" class="order-selection-dialog">
        <!-- 搜索框 -->
        <div class="dialog-search-area">
            <div class="search-input-group">
                <el-input v-model="orderFilter.orderCode" placeholder="请输入单号" clearable prefix-icon="Search"
                    class="search-input" />
                <el-button @click="resetOrderFilter" plain style="margin-left: 12px">
                    <el-icon>
                        <Refresh />
                    </el-icon>重置
                </el-button>
                <el-button type="primary" @click="filterOrders11">
                    <el-icon>
                        <Search />
                    </el-icon>查询
                </el-button>
            </div>
        </div>

        <!-- 表格区域 -->
        <div class="dialog-table-container">
            <el-table :data="filteredOrders" border highlight-current-row style="width: 100%; border-radius: 4px;"
                :cell-style="{ textAlign: 'center', padding: '8px 0' }" :header-cell-style="{
                textAlign: 'center',
                background: 'linear-gradient(to right, #f0f7ff, #e6f7ff)',
                fontWeight: 600,
                color: '#1a73e8',
                fontSize: '14px',
                height: '48px'
            }" :row-style="{ height: '48px' }" @selection-change="handleOrderSelectionChange"
                @row-click="handleOrderSelect">
                <el-table-column type="selection" width="60" align="center" />
                <el-table-column prop="Othoutord_code" label="单号" width="200">
                    <template #header>
                        <div class="column-header">
                            <el-icon>
                                <Document />
                            </el-icon>单号
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="warehouse_name" label="仓库" width="200">
                    <template #header>
                        <div class="column-header">
                            <el-icon>
                                <OfficeBuilding />
                            </el-icon>仓库
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="startdate" label="日期" width="200">
                    <template #header>
                        <div class="column-header">
                            <el-icon>
                                <Calendar />
                            </el-icon>日期
                        </div>
                    </template>
                    <template #default="{ row }">
                        <div class="date-cell">
                            {{ formatDate(row.startdate) }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="create_by" label="创建人" width="200">
                    <template #header>
                        <div class="column-header">
                            <el-icon>
                                <User />
                            </el-icon>创建人
                        </div>
                    </template>
                </el-table-column>

            </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="dialog-pagination">
            <el-pagination v-model:current-page="orderCurrentPage" v-model:page-size="orderPageSize"
                :page-sizes="[5, 10, 20, 50]" :small="true" :background="true"
                layout="total, sizes, prev, pager, next, jumper" :total="orderTotalCount"
                @size-change="handleOrderSizeChange" @current-change="handleOrderCurrentChange" />
        </div>

        <!-- 底部操作区域 -->
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="orderDialogVisible = false" size="medium" plain>
                    <el-icon>
                        <Close />
                    </el-icon>取消
                </el-button>
                <el-button type="primary" size="medium" @click="confirmOrderSelection"
                    :disabled="selectedOrders.length === 0">
                    <el-icon>
                        <Check />
                    </el-icon>确定 ({{ selectedOrders.length }})
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, inject, watch, toRaw } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { debounce } from 'lodash';
import { computed } from 'vue';
import { useWarehouseStore } from '@/storejs/warehouseStore'



const warehouseStore = useWarehouseStore()
const samp_code_cd = warehouseStore.samp_code;


// 出库类型
const options = ref([])
// 仓库库区
const Warhouse_zone = ref([]);
// 库位
const Warehouse_location = ref([]);

const rules = reactive({

    othoutord_type: [
        { required: true, message: '请选择出库类型', trigger: 'change' }
    ],
    warehouse_code: [
        { required: true, message: '请选择出库仓库', trigger: 'change' }
    ],
    othoutord_code_Associated: [
        { required: true, message: '请输入关联单号', trigger: 'blur' }
    ],
    zone_code: [
        { required: true, message: '请选择出库库区', trigger: 'change' }
    ],
    othoutord_wkeep: [
        { required: true, message: '请选择出库员', trigger: 'change' }
    ]
})


let othoutordAdd = {
    othoutord_type: "", // 出库类型
    othoutord_code: "", // 出库单号

    othoutord_wkeep: "", // 出库员
    othoutord_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'), // 出库时间
    othoutord_status: 0, // 出库状态
    warehouse_code: "",
    warehouse_name: "",
    zone_code: "",
    zone_name: "",
    othoutord_code_Associated: "",
    del_flag: '0', // 删除状态
    create_by: localStorage.getItem('userLName'), // 创建人
    create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'), // 创建时间
}

// 模态对象
const othoutord_order = reactive({ ...othoutordAdd })

const ruleFormRef = ref(null)


//出库员
const othoutord_wkeep_List = ref([]);


// 仓库名称查询
const Weahouse = ref([]);


const deptOptions = ref([])
const customerOptons = ref([])
const customer_name = ref("")
const dialogTableVisible = ref(false)
const productData = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const pageCount = ref(0)

const productName = ref("")
const dict_code = ref("0")

const measureOptios = ref([])
const multipleTableRef = ref(null); // 表格引用

const selectedProducts = ref([]); // 存储选中的产品

const selectedTable = ref(null); // 表格引用
const selectedRows = ref([]); // 存储选中的数据
const selectedData = ref([]); // 最终确认选择的数据
const attributeOptios = ref([])
const sale_total_qty = ref(0) // 记录销售总数
const sale_total_price = ref(0) // 记录销售总额
const cost_total_proce = ref(0) // 记录产品成本总额
const router = useRouter()

const SweetAsync = ref({}); // 关联单号的查询

var isDisabledlocation = ref(false); // 下拉框禁用


const orderTypeConfig = {
    1: {
        listApi: 'Inv_trf/Inv_Select_othoutordSelect',
        countApi: 'Inv_trf/Inv_Select_othoutordSelect_Count',
        detailApi: 'Inv_trf/Inv_trf_SelectDetail',
        transformItem: (item) => ({
            Othoutord_code: item.trf_code,
            warehouse_name: item.warehouse_out_name,
            create_by: item.create_by,
            startdate: item.trf_startdate,
            warehouse_code: item.warehouse_out_code,
            stock_entry_no: item.stock_entry_no
        })
    },
    2: {
        listApi: 'Inv_Samp/Inv_Select_SampSelect',
        countApi: 'Inv_Samp/Inv_Select_SmapSelect_Count',
        detailApi: 'Inv_Samp/Inv_Select_Inv_prodInfo',
        transformItem: (item) => ({
            Othoutord_code: item.samp_code,
            warehouse_name: item.warehouse_name,
            create_by: item.create_by,
            startdate: item.samp_audit_time,
            warehouse_code: item.warehouse_code
        })
    },
    3: {
        listApi: 'Inv_Qty/Inv_Qty_Maisbhg_Select',
        countApi: 'Inv_Qty/Inv_Qty_Maisbhg_Select_Count',
        detailApi: 'Inv_Qty/Inv_Qty_SelectMainbhgDetail',
        transformItem: (item) => ({
            Othoutord_code: item.qty_code,
            warehouse_name: item.warehouse_name,
            create_by: item.create_by,
            startdate: item.qty_startdate,
            warehouse_code: item.warehouse_code,
            zone_code: item.zone_code,
            zone_name: item.zone_name
        })
    }
}

const request = (url, params = {}) =>
    axios.get(`http://localhost:5181/api/${url}`, {
        params,
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    })

//判断加载明细表
var PdSelcr = ref(0);

// 控制添加产品的禁用和移出产品的禁用
var InsertisDisabledlocation = ref(false); // 下拉框禁用

watch(selectedData, (newVal) => {
    // 每次计算时清空累加
    sale_total_qty.value = 0
    sale_total_price.value = 0
    cost_total_proce.value = 0
    newVal.forEach(row => {
        if (isNaN(Number(row.sale_qty))) {
            ElMessage.warning('出库数量必须是数字');
            row.sale_qty = 0;
        }

        // 验证销售单价
        if (isNaN(Number(row.pro_sale_price))) {
            ElMessage.warning('出库单价必须是数字');
            row.pro_sale_price = 0;
        }

        if (row.sale_qty > row.inventory_numder) {

            ElMessage.warning(`出库数量不能大于未出库数量(${row.inventory_numder})，已自动修正为未出库数量`);
            row.sale_qty = row.inventory_numder;
        }

        let allFullyShipped = true;

        if (Number(row.sale_qty) !== Number(row.inventory_numder)) {
            allFullyShipped = false;
        }

        PdSelcrPSwer.value = allFullyShipped ? 2 : 1;



        row.pro_total_amount = Number((row.sale_qty || 0) * (row.pro_sale_price || 0)).toFixed(2);
        row.pro_total_cost = Number((row.sale_qty || 0) * (row.pro_cost_price || 0)).toFixed(2);

        sale_total_qty.value += Number(row.sale_qty)
        sale_total_price.value += Number(row.pro_total_amount)
        cost_total_proce.value += Number(row.pro_total_cost)

         // 设置状态：2=全部出库，1=部分出库，3=盘亏出库未全部
    if (othoutord_order.othoutord_type === "3") {
        PdSelcrPSwer.value = allFullyShipped ? 2 : 3;
    } else {
        PdSelcrPSwer.value = allFullyShipped ? 2 : 1;
    }
    });
}, { deep: true });

// 判断是否提示库要全部入库
var PdSelcrPSwer = ref(0);
var PdSelcrInv_prodInfo = ref(0);
// 验证方法
const validateSaleQty = (row) => {
    if (PdSelcr.value === 1) {
        if (row.sale_qty != row.inventory_numder && row.sale_qty != 0) {

            PdSelcrPSwer.value = 1;

        } else {
            PdSelcrPSwer.value = 2;
        }
    }
};

// 关联单号对话框相关状态
const orderDialogVisible = ref(false);
const selectedOrders = ref([]);
const selectedOrder = ref(null); // 存储单选订单
const orderFilter = reactive({
    orderCode: ""
});
// 获取详细信息
// const cpSelectData = ref([]);

// 分页相关
const orderCurrentPage = ref(1);
const orderPageSize = ref(5);
const orderTotalCount = ref(0);

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString();
};



// 过滤订单数据
const filteredOrders = computed(() => {
    const orders = Array.isArray(SweetAsync.value) ? SweetAsync.value : [];
    if (!orderFilter.orderCode) return orders;
    return orders.filter(order =>
        order.Othoutord_code && typeof order.Othoutord_code === 'string'
            ? order.Othoutord_code.includes(orderFilter.orderCode)
            : false
    );
});

// 处理订单选择变化（多选）
const handleOrderSelectionChange = async (val) => {
    selectedOrders.value = val;
};

// 处理行点击（单选）
const handleOrderSelect = (order) => {
    selectedOrder.value = order;
};

// 重置筛选条件
const resetOrderFilter = () => {
    orderFilter.orderCode = "";
    filterOrders();
};

const fetchProductDetails = async (type, orderCode) => {
    const cfg = orderTypeConfig[type]
    if (!cfg) return []
    const key = type === 1 ? 'trf_code' : type === 2 ? 'code' : 'qty_code'
    const { data } = await request(cfg.detailApi, { [key]: orderCode })
    return data || []
}

// 确认选择订单 进行赋值
const confirmOrderSelection = async () => {
    const order = selectedOrder.value || selectedOrders.value[0]
    if (!order) return ElMessage.warning('请选择订单')

    selectedData.value = []
    othoutord_order.othoutord_code_Associated = order.Othoutord_code
    othoutord_order.warehouse_name = order.warehouse_name
    othoutord_order.warehouse_code = order.warehouse_code

    if ([2, 3].includes(Number(othoutord_order.othoutord_type))) {
        othoutord_order.zone_name = order.zone_name
        othoutord_order.zone_code = order.zone_code
    }

    try {
        const products = await fetchProductDetails(Number(othoutord_order.othoutord_type), order.Othoutord_code)
        selectedData.value = await Promise.all(
            products.map(async (item) => {
                const stockNumber = await StockSelect(
                    order.warehouse_code,
                    item.pro_code,
                    item.stock_entry_no || '0'
                )
                const locationRes = await getSelect(order.warehouse_code, item.pro_code, item.stock_entry_no || '0')
                const loc = locationRes.data?.[0] || {}
                othoutord_order.zone_name = loc.zone_Name
                othoutord_order.zone_code = loc.zone_Code

                return {
                    ...item,
                    stock_name: item.pro_name,
                    stock_model: item.pro_model,
                    dict_code: item.unitmeas_id,
                    sale_qty: 0,
                    inventory_numder: (() => {
                        const type = Number(othoutord_order.othoutord_type);
                        if (type === 3) return item.proddti_loss || 0;
                        if (type === 2) return item.prodInfo_totnum_uqual || 0;
                        if (type === 1) return item.inventory_numder || 0;
                        return 0;
                    })(),
                    stock_numder: stockNumber,
                    pro_sale_price: loc.pro_sale_price || item.pro_sale_price || 0,
                    pro_cost_price: loc.pro_cost_price || item.pro_cost_price || 0,
                    location_code: loc.location_Code || '',
                    location_name: loc.location_Name || ''
                }
            })
        )

        if (othoutord_order.zone_code) await getWarehouse_location(othoutord_order.zone_code)
        InsertisDisabledlocation.value = true
        orderDialogVisible.value = false
    } catch (e) {
        ElMessage.error('处理订单时出错')
    }
}

// 根据仓库编码和产品编码查询库存信息
function StockSelect(Waarehouse_code, Pro_code, stock_entry_no) {
    return axios.get("http://localhost:5181/api/Inv_Stock/Getinv_stock_XQ", {
        params: {
            weahouse_code: Waarehouse_code,
            por_code: Pro_code,
            stock_entry_no: stock_entry_no
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((res) => {
        return res.data;
    }).catch((res) => {
        console.log(res);
    })
}



// 点击保存按钮
async function handleAdd() {

    const valid = await ruleFormRef.value.validate().catch(() => false);
    if (!valid) {
        ElMessage.warning('请先完善必填项');
        return;
    }

    const typeName = othoutord_order.othoutord_type === "1" ? '调拨出库' : '报损出库';
    if (PdSelcrPSwer.value == 1) {
        ElMessage.warning(`${typeName}必须全部出库`);
        return;
    }

    if (PdSelcrPSwer.value == 3) {
        ElMessage.warning(`盘亏出库必须全部出库`);
        return;
    }

    try {
        await obtainCode();
        console.log("生成的出库单号:", othoutord_order.othoutord_code);

        othoutord_order.othoutord_status = 0;

        const mainResponse = await axios.put(
            "http://localhost:5181/api/Inv_othoutord/Inv_othoutordAdd",
            othoutord_order,
            { headers: { authorization: `Bearer ${localStorage.getItem('token')}` } }
        );

        if (mainResponse.data > 0) {
            ElMessage.success("保存成功");

            const id = await Select_othoutord_id();
            console.log("生成的出库单id:", id);

            // 添加明细数据
            const detailList = selectedData.value.map(item => ({
                Othoutord_id: id,
                Pro_name: item.stock_name,
                Pro_code: item.pro_code,
                Pro_brand: item.pro_brand,
                unitmeas_id: String(item.dict_code),
                Othwrproddt_numder: Number(item.sale_qty),//出库数量
                Inventory_numder: Number(item.inventory_numder) || 0,
                Pro_model: item.stock_model,

                location_code: item.location_code ? item.location_code.replace(/\r\n/g, "") : "",
                location_name: item.location_name,
                pro_cost_price: Number(item.pro_cost_price),
                pro_sale_price: Number(item.pro_sale_price),
                stock_entry_no: String(item.stock_entry_no || "0"),
            }));

            await Inv_othproddetails_add(detailList);

            selectedData.value = [];
            clearForm();
            isDisabledlocation.value = false;

            router.push('/main/Inv/Inv_othoutordVue');
        } else {
            ElMessage.error("主表保存失败");
        }
    } catch (error) {
        console.error("保存出错:", error);
        ElMessage.error("保存过程中发生错误");
    }
}

// 清空表单数据和下拉框选项的方法
function clearForm() {
    othoutord_order.othoutord_code_Associated = "";
    othoutord_order.othoutord_code = "";
    othoutord_order.othoutord_type = "";
    othoutord_order.warehouse_code = "";
    othoutord_order.warehouse_name = "";
    othoutord_order.zone_code = "";
    othoutord_order.zone_name = "";
}

// 添加详细表
function Inv_othproddetails_add(detailList) {
    axios.put("http://localhost:5181/api/Inv_othoutord/Inv_othproddetails", detailList, {
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((res) => {

    }).catch((res) => {
        console.log(res)
    })
}



// 根据编号查询ID
function Select_othoutord_id() {

    return new Promise((resolve, reject) => {
        axios.get("http://localhost:5181/api/Inv_othoutord/othproddetailsSelect_id", {
            params: {
                otgwr_code: othoutord_order.othoutord_code // 修正参数名
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((res) => {
            resolve(res.data); // 正确返回数据
        }).catch((error) => {
            console.error("获取ID失败:", error);
            reject(error);
        });
    });
}

// 获取编号--生成单号
async function obtainCode() {
    try {
        const result = await axios.get("http://localhost:5181/api/DJBH/DJBH", {
            params: { en_code: 21 },
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        othoutord_order.othoutord_code = result.data;
    } catch (err) {
        console.error("生成单号失败:", err);
        throw err;
    }
}

// 分页大小变化
const handleOrderSizeChange = (val) => {
    orderPageSize.value = val;
    filterOrders();
};

// 当前页码变化
const handleOrderCurrentChange = (val) => {
    orderCurrentPage.value = val;
    filterOrders();
};


const filterOrders11 = async () => {

    await showOrderDialog();
}

//点击报损出库
async function showOrderDialogxians() {

    if (!samp_code_cd) {

        return; // 没有抽检单号就不执行
    }

    // 设置出库类型为“报损出库”
    othoutord_order.othoutord_type = "2";

    // 设置关联单号
    orderFilter.orderCode = samp_code_cd;

    // 设置出库类型为报损出库
    PdSelcr.value = 2;

    // 禁用库区、库位等选择
    //InsertisDisabledlocation.value = true;

    // 打开模态框
    orderDialogVisible.value = true;

    // 加载订单列表
    showOrderDialog();

    //自动选中对应订单（如果存在）
    const targetOrder = filteredOrders.value.find(
        order => order.Othoutord_code === samp_code_cd
    );

    selectedOrders.value = [targetOrder];
    selectedOrder.value = targetOrder;

    warehouseStore.samp_code = "";

    // 模拟点击“确定”按钮，直接进入确认逻辑
    confirmOrderSelection();


    //samp_code_cd="";

}




// 过滤订单（带分页）
const filterOrders = async () => {

    if (PdSelcr.value == 1) {
        // 调拨出库
        await axios.get("http://localhost:5181/api/Inv_trf/Inv_Select_othoutordSelect_Count", {
            params: {
                code: orderFilter.orderCode
            }
        }).then(response => {
            orderTotalCount.value = response.data;
        }).catch(error => {
            console.error(error);
            ElMessage.error('获取订单数据失败');
        });
    } else if (PdSelcr.value == 2) {
        //报损出库
        await axios.get("http://localhost:5181/api/Inv_Samp/Inv_Select_SmapSelect_Count", {
            params: {
                code: orderFilter.orderCode
            }
        }).then(response => {
            orderTotalCount.value = response.data;
        }).catch(error => {
            console.error(error);
            ElMessage.error('获取订单数据失败');
        });
    } else if (PdSelcr.value == 3) {
        //盘亏出库
        await axios.get("http://localhost:5181/api/Inv_Qty/Inv_Qty_Maisbhg_Select_Count", {
            params: {
                code: orderFilter.orderCode
            }
        }).then(response => {
            orderTotalCount.value = response.data;
        }).catch(error => {
            console.error(error);
            ElMessage.error('获取订单数据失败');
        });
    }
}


const showOrderDialog = async () => {
    const type = Number(othoutord_order.othoutord_type)
    if (!orderTypeConfig[type]) return

    try {
        const cfg = orderTypeConfig[type]
        const [listRes, countRes] = await Promise.all([
            request(cfg.listApi, {
                code: orderFilter.orderCode,
                currentPage: orderCurrentPage.value,
                pageSize: orderPageSize.value
            }),
            request(cfg.countApi, { code: orderFilter.orderCode })
        ])

        SweetAsync.value = (listRes.data || []).map(cfg.transformItem)
        orderTotalCount.value = countRes.data || 0
        orderDialogVisible.value = true
    } catch (e) {
        ElMessage.error('加载订单失败')
    }
}

//调拨出库--查询仓库的库位和库区
function getSelect(warehouse_code, pro_code, stock_entry_no) {
    return axios.get("http://localhost:5181/api/Inv_Stock/Get_Select_stock_All_By_Pro_Code", {
        params: {
            weahouse_code: warehouse_code,
            pro_code: pro_code,
            stock_entry_no: stock_entry_no
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    })
}

//var userName = ref("");

function getDept() {
    axios.get("http://localhost:5181/api/Dept/Get_Dept_Trees", {
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        deptOptions.value = convertToTreeOptions(result.data)
    }).catch((err) => {
        console.info(err)
    });
}



// 查询客户信息
function getCustomer() {
    axios.get("http://localhost:5181/api/Sinv_Customer/Sinv_CustomerByName", {
        params: {
            name: customer_name.value
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        customerOptons.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

// 把二维数据转换为结构数据
const convertToTreeOptions = (items) => {
    return items.map(item => ({
        value: item.dept_id,
        label: item.dept_name,
        leader: item.leader,
        children: item.children && item.children.length > 0
            ? convertToTreeOptions(item.children)
            : []
    }))
}

// 获取部门数据
function Depts() {
    axios.get("http://localhost:5181/api/Dept/DeptOpt", {
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        othoutord_wkeep_List.value = convertToTreeOptions(result.data)
    }).catch(console.error)
}






// 获取下拉选项数据
function getClassify() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "inv_othoutord"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        options.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}






// 选择出库事件触发
const handleSelectChange = (selectedValue) => {
    const selectedItem = Weahouse.value.find(item => item.warehouse_code === selectedValue);
    othoutord_order.warehouse_name = selectedItem.warehouse_name;

    axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
        params: {
            warehouse_code: selectedValue
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        Warhouse_zone.value = result.data;
    })
};



// 出库类型选择事件触发
const handleSelecttype = (value) => {
    const selectedItem = options.value.find(item => item.dict_value == value)
    othoutord_order.othoutord_type = selectedItem.dict_value;

    //清空关联单号
    orderFilter.orderCode = "";


    othoutord_order.warehouse_code = '';
    othoutord_order.warehouse_name = '';
    othoutord_order.zone_code = '';
    othoutord_order.zone_name = '';
    selectedData.value = []; // 清空产品明细表

    othoutord_order.othoutord_code_Associated = "";
    if (value == 5) {
        PdSelcr.value = 5;
        InsertisDisabledlocation.value = false;
        productFill();
        productCount();
    }
}

// 选择出库库区的时触发
const handleSzone = (value) => {
    const selectedItemzone = Warhouse_zone.value.find(item => item.zone_code == value)
    othoutord_order.zone_name = selectedItemzone.zone_name;
    isDisabledlocation.value = false;
    getWarehouse_location(value);
}

function getWarehouse_location(value) {

    axios.get("http://localhost:5181/api/Db_warehouse_location/warehouse_location", {
        params: {
            zone_code: value
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        Warehouse_location.value = result.data;
    }).catch((err) => {
        console.info(err)
    })
}

// 选择出库库位的触发事件
const locationEndit = (value, row) => {
    row.location_code = value;
    const selectedItem = Warehouse_location.value.find(item => item.location_code === value);
    row.location_name = selectedItem ? selectedItem.location_name : '';

    if (!selectedItem) {
        ElMessage.error('未找到该库位信息');
        return;
    }


};

function productAdd() {
    dialogTableVisible.value = true
}

// 移除选中的table控件数据
const productDel = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要移除的数据');
        return;
    }

    const selectedCodes = selectedRows.value.map(item => item.pro_code);
    selectedData.value = selectedData.value.filter(
        item => !selectedCodes.includes(item.pro_code)
    );

    if (selectedTable.value) {
        selectedTable.value.clearSelection();
    }

    selectedRows.value = [];
};

// 分页查询产品库存信息
function productFill() {
    if (PdSelcr.value == 5) {
        axios.get("http://localhost:5181/api/Db_Product/Get_Products_Other", {
            params: {
                procode: productName.value,
                Measure_id: dict_code.value,
                currentPage: currentPage.value,
                pageSize: pageSize.value
            },
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then(async (res) => {
            const transformOthwrDataPd = [];
            for (const item of res.data) {
                const stockNumberResponse = await Inv_stock_numfer(item.pro_code);
                const stockNumber = stockNumberResponse.data;

                transformOthwrDataPd.push({
                    ...item,
                    pro_code: item.pro_code,
                    stock_name: item.pro_name,
                    stock_model: item.pro_model,
                    dict_code: item.measure_id,
                    pro_cost_price: item.pro_cost_price,
                    stock_numder: stockNumber
                });
            }
            productData.value = transformOthwrDataPd;
        }).catch((err) => {
            console.info(err);
        });
    } else {
        axios.get("http://localhost:5181/api/Db_warehouse/GetInv_Stock", {
            params: {
                productName: productName.value,
                dict_code: dict_code.value,
                currentPage: currentPage.value,
                pageSize: pageSize.value
            }, headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((result) => {
            productData.value = result.data
        }).catch((err) => {
            console.info(err)
        });
    }
}



// 把部门树 + 用户合并成 cascader 可用的两级数据
async function buildCascaderOptions(deptTree) {
    const options = []

    // 递归遍历部门
    const walk = async (nodes) => {
        for (const dept of nodes) {
            // 拉当前部门下的用户
            const { data: users } = await axios.get('http://localhost:5181/api/User/GetUsers', {
                params: { dept: dept.dept_id },
                headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            })

            // 把用户塞进 children
            const children = users.map(u => ({
                value: u.user_name,   // 最终保存出库员名字
                label: u.user_name    // 级联面板显示名字
            }))

            options.push({
                value: dept.dept_id,
                label: dept.dept_name,
                children
            })

            // 如果还有子部门，继续递归
            if (dept.children?.length) {
                await walk(dept.children)
            }
        }
    }

    await walk(deptTree)
    return options
}


// 查询产品库存总数
function productCount() {
    if (PdSelcr.value == 5) {
        axios.get("http://localhost:5181/api/Db_Product/ProductCount_Other", {
            params: {
                procode: productName.value,
                Measure_id: dict_code.value
            }, headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((result) => {
            pageCount.value = result.data
        }).catch((err) => {
            console.info(err)
        });
    } else {
        axios.get("http://localhost:5181/api/Db_warehouse/Inv_StockCount", {
            params: {
                productName: productName.value,
                dict_code: dict_code.value
            }, headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            }
        }).then((result) => {
            pageCount.value = result.data
        }).catch((err) => {
            console.info(err)
        });
    }
}

function handleSizeChange(val) {
    pageSize.value = val;
    productFill();
}

function handleCurrentChange(val) {
    currentPage.value = val;
    productFill();
}

// 查询计量单位
function getMeasure() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "db_measure"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        measureOptios.value = result.data
        measureOptios.value = [{
            dict_value: "0", dict_label: "请选择单位"
        }, ...result.data]
    }).catch((err) => {
        console.info(err)
    });
}

// 根据计量单位id返回计量单位名称
function measureValue(row) {
    if (!row) return "无";
    const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
    return parentDept ? parentDept.dict_label : "无";
}

// 查询产品属性
function getAttribute() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "db_pro_attribute"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        attributeOptios.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}



// 根据选择条件查询产品库存信息
function productEedit() {
    //alert("已查询",orderFilter.orderCode)
    //console.log("已查询1111111111");
    productFill()
    productCount()
}

// 重置条件查询
function productReaslt() {
    productName.value = ""
    dict_code.value = "0"
    productFill()
    productCount()
}

// 表格选择变化时的处理函数
const handleSelectionChange = (val) => {
    selectedProducts.value = val;
};

// 点击确定存储选择的产品数据
const handleConfirmSelection = () => {
    selectedData.value = [...selectedData.value, ...selectedProducts.value.map(item => ({
        ...item,
        sale_qty: Number(0),
        pro_total_amount: Number(0).toFixed(2),
        pro_total_cost: Number(0).toFixed(2),
        pro_sale_price: Number(item.pro_sale_price || 0).toFixed(2),
        pro_cost_price: Number(item.pro_cost_price || 0).toFixed(2),
    }))];
    dialogTableVisible.value = false
    multipleTableRef.value.clearSelection()
}

// 表格选择变化时处理数据
const handleSelectedChange = (val) => {
    selectedRows.value = val;
};

// 判断以添加过的产品数据不能再次添加
const isDisabled = (row) => {
    return !selectedData.value.some(item => item.pro_code === row.pro_code);
};

// 退出页面并删除当前页面的标签页
const closeTab = inject('closeTab'); // 注入关闭方法
function handleClose() {
    const targetPath = "/main/Inv/Inv_othoutordVue";

    if (closeTab) {
        closeTab(); // 调用父组件提供的关闭方法
    }

    const tabs = inject('editableTabs');
    if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
        tabs.value.push({
            title: "销售订单",
            name: targetPath,
            path: targetPath
        });
    }

    const activeTab = inject('editableTabsValue');
    if (activeTab) {
        activeTab.value = targetPath;
    }

    router.push(targetPath);
}

// 查询仓库信息
function WeahousesSelect() {
    axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
    }).then((res) => {
        Weahouse.value = res.data;
    }).catch((res) => {
        console.log(res)
    })
}

onMounted(async () => {

    getDept()
    getMeasure()
    getAttribute()
    getCustomer()
    productFill()
    productCount()
    getClassify()
    WeahousesSelect()
    Depts()
    //await  showOrderDialogxians()

    // 先加载部门树和人员
    const { data: deptTree } = await axios.get('http://localhost:5181/api/Dept/DeptOpt', {
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    });
    othoutord_wkeep_List.value = await buildCascaderOptions(deptTree);


    // 最后再执行自动弹窗逻辑
    await showOrderDialogxians();
})
</script>
<style scoped>
.search-input-group {
    display: flex;
    align-items: center;
}

.search-input {
    flex: 1;
    max-width: 320px;
    margin: 10px;
}

/* 分页样式 */
.dialog-pagination {
    display: flex;
    justify-content: center;
    padding: 8px 0;
    background: #f9fbfd;
    border-radius: 6px;
}
</style>>